import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/Layout/Index.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: "layout",
    component: Layout,
    // 默认重定向到首页
    redirect:"/home",
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("@/views/Home/Index.vue")
      },
      {
        path: "/menu",
        name: "menu",
        component: () => import("@/views/Menus/Index.vue")
      },
      {
        path: "/role",
        name: "role",
        component: () => import("@/views/Role")
      },
      {
        path: "/user",
        name: "user",
        component: () => import("@/views/Admin")
      },
      {
        path: "/category",
        name: "category",
        component: () => import("@/views/Category")
      }
    ]
  },
  {
    path: '/login',
    name: "login",
    component: () => import("@/views/Login")
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫，判断用户权限
router.beforeEach((to, from, next) => {

  //判断用户有没有登录，如果没有登录，那就跳转到登录页面
  var userinfo = store.state.userinfo;
  console.log(to.path,to.fullPath)
  if (userinfo) {
    //已登录
    if (to.path === '/login') {
      next("/");
    }else if(to.path === "/home"){
      next()
    }else {
      //根据当前访问的路由进行验证权限
      let isauth = userinfo.menus_url.includes(to.fullPath);
      if (isauth) {
        next();
      } else {
        console.log('访问权限受限')
      }
    }
  } else {
    //如果当前访问的路由规则不是登录
    if (to.path != '/login') {
      next('/login')
    } else {
      next();
    }
  }
})


export default router
